<template>
  <div class="zdp-treetable">
    <table class="zdp-treetable__table">
      <!-- 表头 -->
      <thead>
      <tr>
        <th v-for="(column, index) in columns"
            :key="index"
            :style="{ width: column.width || 'auto' }">
          {{ column.label }}
        </th>
        <th v-if="hasActions" style="width: 150px;">操作</th>
      </tr>
      </thead>
      <!-- 表体 -->
      <tbody>
      <TreeTableRow
          v-for="(node, index) in data"
          :key="index"
          :node="node"
          :columns="columns"
          :level="0"
          @toggle="toggleExpand"
      >
        <!-- 操作列插槽 -->
        <template v-if="$slots.actions" #actions="{ node }">
          <slot name="actions" :node="node"></slot>
        </template>
      </TreeTableRow>
      </tbody>
    </table>
  </div>
</template>

<script setup>
import {defineProps, defineEmits, computed, useSlots} from 'vue';
import TreeTableRow from './TreeTableRow.vue'; // 引入子组件

// 定义 Props
const props = defineProps({
  data: {
    type: Array,
    required: true,
  },
  columns: {
    type: Array,
    required: true,
  },
});

// 判断是否有操作列插槽
const hasActions = computed(() => !!useSlots().actions);

// 切换节点展开/折叠状态
const toggleExpand = (node) => {
  node.expanded = !node.expanded;
};
</script>

<style scoped>
.zdp-treetable {
  width: 100%;
  font-family: Arial, sans-serif;
  color: #333;
  border-collapse: collapse;
}

.zdp-treetable__table {
  width: 100%;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.zdp-treetable th,
.zdp-treetable td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #e4e7ed;
}

.zdp-treetable th {
  background-color: #f5f7fa;
  font-weight: bold;
  color: #409eff;
}
</style>